﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using RobotRace.engine.agents;
using RobotRace.engine.agents.implementation;

namespace RobotRaceGUI.AgentConfigurationForms
{
    public partial class SimplePathFollowerConfigurationForm : Form
    {
        public SimplePointFollower agent { get; set; }

        public SimplePathFollowerConfigurationForm()
        {
            InitializeComponent();
        }

        public SimplePathFollowerConfigurationForm(SimplePointFollower agent)
            : this()
        {
            this.agent = agent;
        }

        private void SimplePathFollowerConfigurationForm_Load(object sender, EventArgs e)
        {

        }

        private void applyButton_Click(object sender, EventArgs e)
        {
            double maxVelocity = 1.0;
            double maxDistanceFromCheckpoint = 0.1;

            try
            {
                maxVelocity = Double.Parse(maxVelocityTextBox.Text);
                if (maxVelocity <= 0)
                {
                    throw new Exception("Max velocity cannot be less than or equal to 0!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The value of max velocity does not seem to be valid. Please verify it and try again.");
                return;
            }

            try
            {
                maxVelocity = convertAndThrowIfNotValidDouble(maxVelocityTextBox.Text, "max valocity");
                maxDistanceFromCheckpoint = convertAndThrowIfNotValidDouble(maxAcceptableDistanceTextBox.Text, "max distance from checkpoint");
            }
            catch (ValueNotValidException ex)
            {
                MessageBox.Show("The value of" + ex.FieldName + " does not seem to be valid. Please verify it and try again.");
                return;
            }

            agent.MaxVelocity = maxVelocity;
            agent.AcceptableDistanceFromCheckpoint = maxDistanceFromCheckpoint;

            this.Hide();

        }

        private void SimplePathFollowerConfigurationForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }

        private double convertAndThrowIfNotValidDouble(String value, String fieldName)
        {
            try
            {
                return Double.Parse(value);
            }
            catch (Exception ex)
            {
                throw new ValueNotValidException("Exception while parsing field value!", fieldName);
            }
        }
    }
}
